import SwiftUI
import AVFoundation
import SPGlassKit

public struct GlassVideoPlayerExample: GlassExample {
    public static let componentID = "glass-video-player"
    /// An empty player: the repository ships no media file, so the example shows the states without a video.
    @State private var emptyPlayer = AVPlayer()
    /// A silent clock: it drives the glass controls drawn over a poster.
    @State private var playback = SampleAudioPlayback(duration: 134)

    public init() {}

    public var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                Text("Glass controls over a drawn poster")
                    .font(.headline)
                GlassVideoControls(playback: playback, title: "The Shore House · Trailer") {
                    SampleArtwork(3)
                }

                Text("No player")
                    .font(.headline)
                GlassVideoPlayer(player: nil, accessibilityLabel: "Trailer")

                Text("Player without an item, 4:3")
                    .font(.headline)
                GlassVideoPlayer(player: emptyPlayer, aspectRatio: 4.0 / 3.0, accessibilityLabel: "Lecture recording")

                Text("Missing URL")
                    .font(.headline)
                GlassVideoPlayer(url: nil)

                Text("Sample data · give the player a real URL to see the system controls.")
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
            .padding()
        }
        .task(id: playback.isPlaying) {
            // The fake engine has no clock of its own: tick it while it is "playing".
            while playback.isPlaying, !Task.isCancelled {
                try? await Task.sleep(for: .milliseconds(500))
                if !Task.isCancelled { playback.advance(by: 0.5) }
            }
        }
    }
}

#Preview("GlassVideoPlayer") { GlassVideoPlayerExample().glassTheme(.obsidian) }
